<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="findCurrent">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表
		-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
		</el-table-column>
			<el-table-column prop="username" label="用户名" width="100" sortable>
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="100" sortable>
			</el-table-column>
			<el-table-column prop="phone" label="电话号码" width="140" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="140" sortable>
			</el-table-column>
			<el-table-column prop="state" label="用户状态" width="100" sortable>
				<template scope="scope">
					<span style="color: #11b95c" size="small" v-if="scope.row.state === 1" >启用</span>
					<span style="color:  red" size="small" v-else-if="scope.row.state === 0">注销</span>
					<span style="color: #cf9236" size="small" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="department.name" label="所属部门" width="100" sortable>
			</el-table-column>
			<el-table-column prop="shop.name" label="店铺名称" width="100" sortable>
			</el-table-column>
			<el-table-column label="操作" >
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<!--<el-pagination layout="prev, pager, next" @current-change="getEmployees" :page-size="5" :total="total" :current-page="currentPage" style="float:right;">-->
			<!--</el-pagination>-->
			<el-pagination
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-size="pageSize"
					layout="prev, pager, next"
					:total="total"
					style="float:right;"
			>
			</el-pagination>
		</el-col>

		<!--编辑界面
			:visible.sync 控制当前窗口是否显示
			:rules  表单校验规则
			ref  给当前表单引用一个别名
		-->
		<el-dialog :title="title" :visible.sync="employeeFormVisible" :close-on-click-modal="false">
			<el-form :model="employeeForm" label-width="80px" :rules="employeeFormRules" ref="employeeForm">

				<!-- prop="name" 申明表单属性 叫 name -->
				<el-form-item label="用户名" prop="username">
					<el-input v-model="employeeForm.username" auto-complete="off"/>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="employeeForm.email" auto-complete="off"/>
				</el-form-item>
				<el-form-item label="电话号码" prop="phone">
					<el-input v-model="employeeForm.phone" auto-complete="off"/>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="employeeForm.password" auto-complete="off"/>
				</el-form-item>
				<el-form-item label="年龄" prop="age">
					<el-input v-model="employeeForm.age" auto-complete="off"/>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="employeeForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">注销</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="所属部门" >
					<!--<el-input v-model="employeeForm.department" auto-complete="off"/>-->
					<!--
						el-option  选择项
					  	item  遍历后得到的值
					  	:label 选择后展示在选择框中的内容
					  	:value 选择后要传给后端的值
					-->
					<el-cascader v-model="employeeForm.department"
								 :options="deptTree"
								 :props="{
							 checkStrictly: true,
							 label:'name',
							 value:'id'
							 }"
								 clearable/>
				</el-form-item>
				<el-form-item label="店铺名称">
					<!--<el-input v-model="employeeForm.shop" auto-complete="off"/>-->
					<!--
						el-option  选择项
					  	item  遍历后得到的值
					  	:label 选择后展示在选择框中的内容
					  	:value 选择后要传给后端的值
					 -->
					<el-select v-model="employeeForm.shop" value-key="id" clearable placeholder="请选择">
						<el-option
								v-for="item in shops"
								:key="item.id"
								:label="item.name"
								:value="item">
							<span style="float: left">{{ item.name }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.address }}</span>
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click.native="employeeFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="employeeSubmit" :loading="employeeLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getEmployeeListPage, removeEmployee, batchRemoveEmployee, editEmployee, addEmployee } from '../../api/api';

	export default {
        data() {
            // 电话号码格式校验
            var checkPhone = (rule, value, callback) => {
                const phoneReg = /^1[3-9][0-9]{9}$/
                if (!value) {
                    return callback(new Error('电话号码不能为空'))
                }
                setTimeout(() => {
                    // Number.isInteger是es6验证数字是否为整数的方法,实际输入的数字总是识别成字符串
                    // 所以在前面加了一个+实现隐式转换
                    if (!Number.isInteger(+value)) {
                        callback(new Error('请输入数字值'))
                    } else {
                        if (phoneReg.test(value)) {
                            callback()
                        } else {
                            callback(new Error('电话号码格式不正确'))
                        }
                    }
                }, 100)
            }
            return {
                filters: {
                    keyword: ''
                },
                employees: [],
                shops: [],
                deptTree: [],
                currentPage: 1,
                total: 0,
                pageSize: 5,
                title: "",
                listLoading: false,
                sels: [],//列表选中行  所有选中对的行都会传进来

                employeeFormVisible: false,//编辑界面是否显示
                employeeLoading: false,
                employeeFormRules: {
                    username: [
                        {required: true, message: '你还输入名字哦，亲', trigger: 'blur'}
                    ],
                    phone: [
                        {validator: checkPhone, trigger: 'blur'}
                    ]
                },
                //表单数据数据绑定到模型层
                employeeForm: {
                    id: null,
                    username: '',
                    email: '',
                    phone: '',
                    password: '',
                    age: '',
                    state: 1,
                    department:null,
                    shop:null,
                },
            }
        },
        methods: {
			// 解决高级查询跳转第一页
            findCurrent(){
                this.currentPage = 1;
                this.getEmployees();
			},
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getEmployees();
            },
            //获取用户列表 分页展示
            getEmployees() {
                // alert(currentPage)
                //  if (currentPage){
                //      this.currentPage=currentPage
                // }
                let para = {
                    currentPage: this.currentPage,
                    keyword: this.filters.keyword, // 高级查询
                    pageSize: this.pageSize
                };
                console.log(para)
                this.listLoading = true; // 开启忙等框
                this.$http.post("/employee", para)
                    .then(result => {
                        result = result.data;
                        this.employees = result.rows;
                        this.total = result.total; // 动态获取总条数
                        this.listLoading = false; // 关闭忙等框
                    }).catch(result => {
                    console.log(result);
                    alert("系统错误！");
                })
            },

            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '温馨提示', {
                    type: 'warning'
                }).then(() => {// 点击确定
                    this.listLoading = true;// 打开忙等框
                    //NProgress.start();
                    //let para = { id: row.id };
                    this.$http.delete("/employee/" + row.id).then(result => {
                        //关闭加载效果
                        this.listLoading = false;// 关闭忙等框
                        result = result.data; // AjaxResult
                        //删除成功提示
                        if (result.success) {
                            this.$message({
                                message: '删除成功！',
                                type: 'success'
                            });
                            // 当前页之前的数据总条数
                            let count = (this.currentPage - 1) * this.pageSize;
                            // 删除操作后全部数据总条数
                            let nowTotal = this.total - 1;
                            if(count == nowTotal&&this.currentPage!=1){
								this.currentPage = this.currentPage-1;
                                //重新加载列表数据
                                this.getEmployees();
							}else if((nowTotal-count)>0){
								this.currentPage = this.currentPage;
                                //重新加载列表数据
                                this.getEmployees();
							};

                        } else {
                            //删除失败提示
                            this.$message({
                                message: result.message,
                                type: 'error'
                            });
                            this.currentPage = this.currentPage
                            //重新加载列表数据
                            this.getEmployees();
                        }
                    }).catch(result => {
                        //失败提示
                        this.$message({
                            message: result.message,
                            type: 'error'
                        });
                        this.currentPage = 1;
                        //重新加载列表数据
                        this.getEmployees();
                    });
                }).catch(() => {

                });
            },

            //显示编辑界面
            handleEdit: function (index, row) {
                this.getDeptTree();
                this.title = "编辑"
                this.employeeFormVisible = true;
                this.employeeForm = Object.assign({}, row); // 克隆回显
				// 数据回显
				this.employeeForm.department =row.department_id;
            },
            //显示新增界面
            handleAdd: function () {
                this.getDeptTree();
                this.title = "新增"
                this.employeeFormVisible = true;
                this.employeeForm = { // 清空
                    id: null,
                    username: '',
                    email: '',
                    phone: '',
                    password: '',
                    age: '',
                    state: 1,
                    department:null,
                    shop:null,
                };
            },

            //编辑或者新增 提交表单
            employeeSubmit: function () {
                // 主动开启表单校验
                this.$refs.employeeForm.validate((valid) => {
                    if (valid) {// 校验通过
                        this.$confirm('确认提交吗？', '提示', {}).then(() => { // 点击确认
                            this.employeeLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.employeeForm);// 克隆一份表单数据
							console.log(para.department)
                           // 处理后台数据格式
                            if (para.department) { // 非空判断
                                let department = para.department;// id数组
                                // 拿到数组的最后一位
                                let pad = department[department.length - 1]
                                // 重新赋值给para 重新封装对象
                                para.department = {"id": pad};
                            }
                            this.$http.put("/employee", para)
                                .then(result => {
                                    this.employeeLoading = false;// 关闭忙等
                                    this.employeeFormVisible = false; // 关闭弹出
                                    result = result.data; // AjaxResult
                                    if (result.success) {
                                        this.$message({
                                            message: '操作成功！',
                                            type: 'success'
                                        });
                                    } else {
                                        //操作失败提示
                                        this.$message({
                                            message: result.message,
                                            type: 'error'
                                        });
                                    }
                                    this.currentPage = 1;
                                    //重新加载列表数据
                                    this.getEmployees();
                                }).catch(result => {
                                this.employeeLoading = false;// 关闭忙等
                                this.$message({
                                    message: "操作失败",
                                    type: 'error'
                                });
                            })
                        });
                    }
                });
            },

            selsChange: function (sels) { // 所以选中的对象都会传进来
                this.sels = sels;
                console.log(sels)
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => { // 点击确定
                    this.listLoading = true; // 打开忙等框
                    //NProgress.start();
                    // let para = { ids: ids };

                    // axios发送Ajax请求
                    this.$http.patch("/employee", ids).then(result => {
                        //关闭加载效果
                        this.listLoading = false;
                        result = result.data; // AjaxResult
                        //删除成功提示
                        if (result.success) {
                            this.$message({
                                message: '删除成功！',
                                type: 'success'
                            });
                            // 当前页之前的数据总条数
                            let count = (this.currentPage - 1) * this.pageSize;
                            // 删除操作后全部数据总条数
                            let nowTotal = this.total - ids.length;
                            if(count == nowTotal&&this.currentPage!=1){
                                this.currentPage = this.currentPage-1;
                                //重新加载列表数据
                                this.getEmployees();
                            }else if((nowTotal-count)>0){
                                this.currentPage = this.currentPage;
                                //重新加载列表数据
                                this.getEmployees();
                            };
                        } else {
                            //删除失败提示
                            this.$message({
                                message: result.message,
                                type: 'error'
                            });
                            this.currentPage = this.currentPage;
                            //重新加载列表数据
                            this.getEmployees();
                        }
                    }).catch(result => { // 点击取消
                        //失败提示
                        this.$message({
                            message: result.message,
                            type: 'error'
                        });
                        this.currentPage = 1;
                        //重新加载列表数据
                        this.getEmployees();
                    });
                    // batchRemoveEmployee(para).then((res) => {
                    // 	this.listLoading = false;
                    // 	//NProgress.done();
                    // 	this.$message({
                    // 		message: '删除成功',
                    // 		type: 'success'
                    // 	});
                    // 	this.getEmployees();
                    // });
                }).catch(() => {

                });
            },

            // 获取部门列表 集合
            getShop() {
                this.$http.get("/shop")
                    .then(reslut => {
                        reslut = reslut.data; // List<Shop>
                        this.shops = reslut;
                    })
            },
            // 获取上级部门树
            getDeptTree() {
                this.$http.get("/employee/tree")
                    .then(result => {
                        console.log(result)
                        result = result.data;
                        this.deptTree = result;
                    })
            }
        },
        mounted() {
            this.getEmployees();
            this.getShop(); // 页面加载完成调用
        },
    }
</script>

<style scoped>

</style>